/**
 * WebSocket服务类
 * 处理实时通信功能
 */

const { getConfig } = require('./config.js');
const apiService = require('./apiService.js');

class WebSocketService {
  constructor() {
    this.ws = null;
    this.isConnected = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
    this.heartbeatInterval = 30000;
    this.heartbeatTimer = null;
    
    const config = getConfig();
    this.wsUrl = config.wsUrl;
    this.debug = config.debug;
    
    // 事件监听器
    this.listeners = new Map();
  }

  /**
   * 连接WebSocket
   * @param {String} roomId 房间ID
   */
  connect(roomId) {
    if (this.isConnected) {
      return;
    }

    try {
      this.ws = wx.connectSocket({
        url: this.wsUrl,
        success: () => {
        },
        fail: (error) => {
          this.handleConnectionError();
        }
      });

      this.ws.onOpen = () => {
        this.isConnected = true;
        this.reconnectAttempts = 0;
        
        // 发送认证信息
        this.authenticate();
        
        // 加入房间
        if (roomId) {
          this.joinRoom(roomId);
        }
        
        // 开始心跳
        this.startHeartbeat();
        
        // 触发连接成功事件
        this.emit('connected');
      };

      this.ws.onMessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this.handleMessage(data);
        } catch (error) {
        }
      };

      this.ws.onClose = () => {
        this.isConnected = false;
        this.stopHeartbeat();
        
        // 触发断开连接事件
        this.emit('disconnected');
        
        // 尝试重连
        this.attemptReconnect(roomId);
      };

      this.ws.onError = (error) => {
        this.handleConnectionError();
      };

    } catch (error) {
      this.handleConnectionError();
    }
  }

  /**
   * 断开连接
   */
  disconnect() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    this.isConnected = false;
    this.stopHeartbeat();
  }

  /**
   * 发送认证信息
   */
  authenticate() {
    const token = apiService.getToken();
    if (token) {
      this.send({
        type: 'auth',
        token: token
      });
    }
  }

  /**
   * 加入房间
   * @param {String} roomId 房间ID
   */
  joinRoom(roomId) {
    this.send({
      type: 'join_room',
      room_id: roomId
    });
  }

  /**
   * 离开房间
   * @param {String} roomId 房间ID
   */
  leaveRoom(roomId) {
    this.send({
      type: 'leave_room',
      room_id: roomId
    });
  }

  /**
   * 发送消息
   * @param {Object} data 消息数据
   */
  send(data) {
    if (this.isConnected && this.ws) {
      try {
        this.ws.send({
          data: JSON.stringify(data),
          success: () => {
            if (this.debug) {
            }
          },
          fail: (error) => {
          }
        });
      } catch (error) {
      }
    } else {
    }
  }

  /**
   * 处理接收到的消息
   * @param {Object} data 消息数据
   */
  handleMessage(data) {
    if (this.debug) {
    }

    // 处理心跳响应
    if (data.type === 'pong') {
      return;
    }

    // 触发对应的事件
    this.emit(data.type, data);
  }

  /**
   * 开始心跳
   */
  startHeartbeat() {
    this.stopHeartbeat();
    this.heartbeatTimer = setInterval(() => {
      this.send({
        type: 'ping'
      });
    }, this.heartbeatInterval);
  }

  /**
   * 停止心跳
   */
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  /**
   * 尝试重连
   * @param {String} roomId 房间ID
   */
  attemptReconnect(roomId) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      
      setTimeout(() => {
        this.connect(roomId);
      }, this.reconnectInterval);
    } else {
      this.emit('reconnect_failed');
    }
  }

  /**
   * 处理连接错误
   */
  handleConnectionError() {
    this.isConnected = false;
    this.stopHeartbeat();
    this.emit('error');
  }

  /**
   * 添加事件监听器
   * @param {String} event 事件名
   * @param {Function} callback 回调函数
   */
  on(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event).push(callback);
  }

  /**
   * 移除事件监听器
   * @param {String} event 事件名
   * @param {Function} callback 回调函数
   */
  off(event, callback) {
    if (this.listeners.has(event)) {
      const callbacks = this.listeners.get(event);
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
    }
  }

  /**
   * 触发事件
   * @param {String} event 事件名
   * @param {*} data 事件数据
   */
  emit(event, data) {
    if (this.listeners.has(event)) {
      const callbacks = this.listeners.get(event);
      callbacks.forEach(callback => {
        try {
          callback(data);
        } catch (error) {
        }
      });
    }
  }

  /**
   * 获取连接状态
   * @returns {Boolean} 是否已连接
   */
  getConnectionStatus() {
    return this.isConnected;
  }
}

// 创建单例实例
const websocketService = new WebSocketService();

module.exports = websocketService;
